#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ioctl.h>
#include "CIpodLog.h"
#include "CIpodEvent.h"
#include "CIpodNative.h"

#define IPOD_EA_NATIVE_HANDLE       "/dev/hhh_ea_native_transport"

int CIpodNative::s_NativeHandle = 0;

int CIpodNative::init() {
    int handle = open(IPOD_EA_NATIVE_HANDLE, O_RDWR);
    if (handle < 0) {
        CIpodLog::e("CIpodNative::init, native handle open failed!\n");
        return -1;
    } else {
        s_NativeHandle = handle;
        CIpodLog::i("CIpodNative::init, native handle open success! s_NativeHandle = %d\n", s_NativeHandle);
    }
    return 0;
}

int CIpodNative::deinit() {
    int ret = -1;
    if (s_NativeHandle > 0) {
        ret = close(s_NativeHandle);
        s_NativeHandle = 0;
    }
    return ret;
}

int CIpodNative::getHandle() {
    return s_NativeHandle;
}

int CIpodNative::getNativeState() {
    return ioctl(s_NativeHandle, 0, NULL);
}

void CIpodNative::registerSigioHandle() {
    int oflags = 0;
    signal(SIGIO, sigioHandle);
    fcntl(s_NativeHandle, F_SETOWN, getpid());
    oflags = fcntl(s_NativeHandle, F_GETFL);
    fcntl(s_NativeHandle, F_SETFL, oflags | FASYNC);
}

void CIpodNative::sigioHandle(int sig) {
    int ret = ioctl(s_NativeHandle, 0, NULL);
    CIpodEvent::sendEvent(IPOD_EVT_EA_NATIVE_STATE_CHANGED, 0, ret);
}
